import axios from 'axios';
import qs from 'qs';

let token = function() {
    return localStorage.getItem('token');
};

let axiosIns = axios.create({});

if (process.env.NODE_ENV == 'development') {
    axiosIns.defaults.baseURL = '/';
} else if (process.env.NODE_ENV == 'debug') {
    axiosIns.defaults.baseURL = '/';
} else if (process.env.NODE_ENV == 'production') {
    axiosIns.defaults.baseURL = '/';
}

axiosIns.defaults.headers.post['X-Requested-With'] = 'XMLHttpRequest';
axiosIns.defaults.headers.get['X-Requested-With'] = 'XMLHttpRequest';
axiosIns.defaults.responseType = 'json';
axiosIns.defaults.transformRequest = [function(data) {
    //数据序列化
    return qs.stringify(data);
}];
axiosIns.defaults.validateStatus = function(status) {
    return true;
};
axiosIns.interceptors.request.use(function(config) {
    //配置config
    config.headers.Accept = 'application/json';
    config = { showLoading: true };
    // config.headers.System = 'vue';
    // let token = Vue.localStorage.get('token');
    if (token()) {
        config.headers.Token = token();
    }
    return config;
});
axiosIns.interceptors.response.use(function(response) {
    let data = response.data;
    let status = response.status;
    if (status === 200) {
        return Promise.resolve(response);
    } else {
        return Promise.reject(response);
    }
});

let ajaxMethod = ['get', 'post'];
let api = {};
ajaxMethod.forEach((method) => {
    // console.log(method, "%%%")
    //数组取值的两种方式
    api[method] = function(uri, data, config = { showLoading: true }) {
        return new Promise(function(resolve, reject) {
            axiosIns[method](uri, data, config).then((response) => {
                if (response.status) {
                    resolve(response);

                } else {
                    resolve(response);
                }
            }).catch((response) => {
                reject(response)
            })
        })
    }
});

export default api;